package cn.my.framework.example;

import cn.my.framework.util.ConstantData;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by zhangl_lc on 2017/8/9.
 */
@Controller
@RequestMapping("/example")
public class ExampleController {

    Logger logger = LoggerFactory.getLogger(ExampleController.class);

    @RequestMapping("/edit/upload")
    @ResponseBody
    public Map<String,Object> uploadForEdit(
            MultipartFile file, HttpServletRequest req,HttpServletResponse resp){
        resp.setHeader("X-Frame-Options","SAMEORIGIN");
        resp.setHeader("Access-Control-Allow-Origin", "*");
        String wang = req.getParameter("wang");
        boolean wangE = StringUtils.isNoneBlank(wang) ? true : false;
        logger.info("...... The Editor is WangEditor ? {}",wangE);
        Map<String,Object> retMap = new HashMap<>();
        retMap.put("code",0);
        retMap.put("msg","图片上传");
        //for wang editor
        if(wangE){
            retMap.put("errno",0);
        }
        if(file != null){
            try {
               /* try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/
                String id = UUID.randomUUID().toString();
                /*String fileName = file.getOriginalFilename();
                String suffix = file.getOriginalFilename().substring(fileName.indexOf("."));
                final String newName = id + suffix;*/
                IOUtils.copy(file.getInputStream(),new FileOutputStream(new File(ConstantData.uploadPath,id)));
                HashMap<String,String> dataMap = new HashMap<>();
                if(wangE){
                    retMap.put("data",new String[]{req.getContextPath()+"/example/edit/load/"+file.getContentType().replaceAll("/","_")+"/"+id});
                }else{
                    dataMap.put("src",req.getContextPath()+"/example/edit/load/"+file.getContentType().replaceAll("/","_")+"/"+id);
                    dataMap.put("title",file.getOriginalFilename());
                    retMap.put("data", dataMap);
                }

                logger.info("..... retMap = {}",retMap);
            } catch (IOException e) {
                e.printStackTrace();
                retMap.put("code",2);
                retMap.put("msg",e.getMessage());
                if(wangE){
                    retMap.put("errno",-1);
                }
            }
        }
        return retMap;
    }

    @RequestMapping("/edit/load/{contentType}/{name}")
    public void loadFileForEdit(
            @PathVariable String contentType, @PathVariable String name,HttpServletResponse resp){
        logger.info(".....load File For Edit.....name : {},contentType{}",name,contentType);
        File file = new File(ConstantData.uploadPath,name);
        if(file.exists()){
            try {
                resp.setContentType(contentType.replaceAll("_","/"));
                FileUtils.copyFile(file,resp.getOutputStream());
                resp.flushBuffer();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/redirect")
    public String redirectPage(HttpServletResponse resp){
        logger.info("----- redirect ----");
        String redirect_url = "http://www.iteye.com";
        Cookie cookie = new Cookie("TEST_TOKIN","thisiscool");
        cookie.setMaxAge(10000);
        resp.addCookie(cookie);
        try {
            resp.setContentType("text/html; charset=UTF-8");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("X-Frame-Options", "SAMEORIGIN");
            //@header('P3P: CP="CAO PSA OUR"');
            /*resp.sendRedirect("http://www.iteye.com");
            resp.setStatus(302);
            resp.setHeader("location",redirect_url);*/
            String html = "<script type='text/javascript'>location.href='"+redirect_url+"';</script>";
            resp.getWriter().print(html);
            resp.getWriter().flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/setcookie")
    public void setCookie(@RequestParam String cookie,HttpServletResponse resp){
        logger.info("----- set cookie : {} -----",cookie);
        Cookie myCookie = new Cookie("mycookie",cookie);
        //cookie.setMaxAge(10000);
        resp.addCookie(myCookie);
    }

    @RequestMapping(value = "ck/upload")
    public void uplodaImageForCk(
            @RequestParam("upload") MultipartFile file,
            HttpServletRequest req, HttpServletResponse resp) {
        String CKEditorFuncNum = req.getParameter("CKEditorFuncNum");
        logger.info(".....CKEditorFuncNum = {}",CKEditorFuncNum);
        PrintWriter out = null;
        resp.setContentType("text/html; charset=UTF-8");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("X-Frame-Options", "SAMEORIGIN");
        try {
            out = resp.getWriter();
            String path = ConstantData.uploadPath;
            String fileName = file.getOriginalFilename();
            String uploadContentType = file.getContentType();
            logger.info("the upload path = {},originalFileName = {},contentType = {}",path,fileName,uploadContentType);
            String imgSuffix = "";
            if (uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg")) {
                imgSuffix = ".jpg";
            } else if (uploadContentType.equals("image/png") || uploadContentType.equals("image/x-png")) {
                // IE6上传的png图片的headimageContentType是"image/x-png"
                imgSuffix = ".png";
            } else if (uploadContentType.equals("image/gif")) {
                imgSuffix = ".gif";
            } else if (uploadContentType.equals("image/bmp")) {
                imgSuffix = ".bmp";
            } else {
                out.println("<script type=\"text/javascript\">");
                out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",''," + "'文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）');");
                out.println("</script>");
                return;
            }
            logger.info("the image file suffix = {}",imgSuffix);
            if (file.getSize() > 1024 * 1024 * 2) {
                out.println("<script type=\"text/javascript\">");
                out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",''," + "'文件大小不得大于2M');");
                out.println("</script>");
                return;
            }
            String uploadFileName = UUID.randomUUID().toString();
            IOUtils.copy(file.getInputStream(),new FileOutputStream(new File(ConstantData.uploadPath,uploadFileName)));
            String imgPath = req.getContextPath()+"/example/edit/load/"+file.getContentType().replaceAll("/","_")+"/"+uploadFileName;
            // 返回"图像"选项卡并显示图片 request.getContextPath()为web项目名
            out.println("<script type=\"text/javascript\">");
            out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",'" + imgPath + "','')");
            out.println("</script>");
            return;
        } catch (Exception e) {
            e.printStackTrace();
            if(out != null){
                String outInfo = "<script type=\"text/javascript\">";
                outInfo += "window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",'上传发生异常','')";
                outInfo += "</script>";
                out.print(outInfo);
                out.flush();
            }
        }finally {
            out.flush();
            out.close();
        }
    }
}
